from rest_framework import serializers

from business.models import Item, Order, Comment
from user.models import User


class ItemSerializer(serializers.ModelSerializer):

    class Meta:
        model = Item
        fields = ('id', 'name', 'single_price', 'shop', 'info')
        read_only_fields = ('id', 'shop')  # 只读字段


class ItemIdSerializer(serializers.ModelSerializer):

    class Meta:
        model = Item
        fields = ('id', )
        read_only_fields = ('id', )


class OrderIdSerializer(serializers.ModelSerializer):

    class Meta:
        model = Order
        fields = ('id', )
        read_only_fields = ('id', )


class CommentSerializer(serializers.ModelSerializer):
    username = serializers.SerializerMethodField()

    def get_username(self, obj):
        def get_username(self, obj):
            sender = User.objects.get(id=obj['sender_id'])
            return sender.username

    class Meta:
        model = Comment
        fields = ('username', 'rating', 'comment')
